import React from "react";
import {Router, Route} from "dva/router";
import PropTypes from "prop-types";
import App from "./routes/App";
import {NotFound, PermDenied, Login} from "./routes/system";

const registerModel = (app, model) => {
  if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) {
    app.model(model)
  }
}

const Routers = ({history, app}) => {

  const routes = [{
    path: '/',
    component: App,
    getIndexRoute(nextState, callback) {
      require.ensure([], require => {
        registerModel(app, require('./models/app'))
        callback(null, {component: require('./routes/Home')})
      })

    },
    childRoutes: [{
      path: 'noperm',
      component: PermDenied
    }, {
      path: 'login',
      component: Login
    }, {
      path: 'setup',
      getComponent(nextState, callback) {
        require.ensure([], require => {
          callback(null, require('./routes/setup/Setup'))
        })
      },
      childRoutes: [{
        path: 'user',
        getComponent(nextState, callback) {
          require.ensure([], require => {
            registerModel(app, require('./models/user'));
            callback(null, require('./routes/setup/User'))
          })
        }
      }, {
        path: 'role',
        getComponent(nextState, callback) {
          require.ensure([], require => {
            registerModel(app, require('./models/role'));
            callback(null, require('./routes/setup/Role'))
          })
        }
      }, {
        path: 'dep',
        getComponent(nextState, callback) {
          require.ensure([], require => {
            registerModel(app, require('./models/dep'));
            callback(null, require('./routes/setup/Dep'))
          })
        }
      }]
    }, {
      path: 'home',
      getComponent(nextState, callback) {
        require.ensure([], require => {
          callback(null, require('./routes/Home'))
        })
      }
    }]
  }, {
    path: '*',
    component: NotFound
  }]

  return <Router history={history} routes={routes}/>;

}

Routers.propTypes = {
  history: PropTypes.object,
  app: PropTypes.object
}

export default Routers
